package com.demo.netty;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory;
import org.jboss.netty.channel.local.DefaultLocalServerChannelFactory;
import org.jboss.netty.channel.local.LocalAddress;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.util.HashedWheelTimer;

import java.util.Scanner;

public class LocalServerClient {
    public static void execution() {
        ServerBootstrap sb = new ServerBootstrap();
        // 设置niosocket工厂
        sb.setFactory(new DefaultLocalServerChannelFactory());
        sb.getPipeline().addLast("serverHandler", new ServerHandler());
        sb.bind(new LocalAddress(10081));

        final int port = 10081;
        // 服务类
        final ClientBootstrap cb = new ClientBootstrap();

        cb.setFactory(new DefaultLocalClientChannelFactory());
        // 管道工厂
        cb.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decoder", new StringDecoder());
                pipeline.addLast("encoder", new StringEncoder());
                pipeline.addLast("clientHandler", new ClientHandler(cb, new HashedWheelTimer()));
                return pipeline;
            }
        });
        cb.setOption("tcpNoDelay", true);
        // 连接服务端
        ChannelFuture connect = cb.connect(new LocalAddress(port));
        Channel channel = connect.getChannel();

        MessageType messageType = new MessageType();
        messageType.setContext("hello server");
        messageType.setType(1);

        channel.write(messageType);
        System.out.println("ClientBootstrap = "+cb);
    }
}
